<!--
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2020-01-12 22:16:05
 * @LastEditors: cxguo
 * @LastEditTime: 2020-07-24 14:16:32
 -->
<template>
  <div @mouseenter="onMouseEnter" @mouseleave="onMouseLeave">
    <el-input
      ref="input"
      v-model="insideVal"
      @focus="onFocus"
      @keydown.native="onkeydown"
      @blur="onblur"
    >
      <i slot="suffix" class="el-icon-arrow-down" />
    </el-input>
    <div v-if="isShowDrop" class="optionsWrapper">
      <ul>
        <li v-for="(item, index) in optionsData" :key="item.value">
          <a :class="{current: currentIndex === index}" @click="() => {btnOptionClick(item)}">{{ item.label }}</a>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import { getPriceBySkuAndUnit } from '@/api/goods/goods-sku.js'
import { getPriceOptions } from '@/config/price.js'

export default {
  props: {
    value: {
      type: [String, Number],
      default: null
    },
    options: {
      type: Array,
      default: () => { return [] }
    },
    /**
     * 行数据
     */
    row: {
      type: Object,
      default: () => { return {} }
    },
    /**
     * 价格下拉框展示的数据过滤（如：销售价，批发价）
     */
    priceCat: {
      type: Array,
      default: () => { return [] }
    },
    /**
     * 默认给他设置一个x什么类型的价格（比如销售价）
     */
    defaultPriceCat: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      insideVal: null,
      currentIndex: 0,
      isShowDrop: false,
      optionsData: []
    }
  },
  watch: {
    value: {
      handler(val) {
        this.insideVal = val
      },
      immediate: true
    },
    'row.unitId': {
      handler(val) {
        const unitId = val
        const skuId = this.row.skuId
        this.getPriceByUnitId({ unitId, skuId })
      }
    },
    'options': {
      handler(data) {
        if (data) this.optionsData = data
      },
      immediate: true
    }
  },
  destroyed() {
  },
  methods: {
    btnOptionClick(row) {
      this.handleSelectOption(row)
    },
    handleSelectOption(row) {
      const { price } = row
      this.$emit('change', row)
      this.$emit('input', price)
      this.isShowDrop = false
    },
    onMouseEnter(e) {
      this.isShowDrop = true
      const optionsData = this.optionsData || []
      if (optionsData.length === 0) {
        const unitId = this.row.unitId
        const skuId = this.row.skuId
        this.getPriceByUnitId({ unitId, skuId })
      }
    },
    onMouseLeave(e) {
      this.isShowDrop = false
    },
    getPriceByUnitId({ skuId, unitId }) {
      const params = { skuId, unitId }
      if (!skuId) return this.$message.error('商品ID不能为空！')
      if (!unitId) return this.$message.error('商品单位ID不能为空！')
      const priceCat = this.priceCat
      getPriceBySkuAndUnit(params).then(res => {
        if (!res.data.flag) return this.$message.error('价格获取失败！')
        const data = res.data.data
        const { price } = data
        const priceOptions = getPriceOptions(price, priceCat)
        this.optionsData = priceOptions
        this.$set(this.row, 'priceStr', price)
        this.setDefaultPrice(price)
      })
    },
    setDefaultPrice(priceStr) {
      const priceObj = JSON.parse(priceStr)
      const defaultPriceCat = this.defaultPriceCat
      const price = priceObj[defaultPriceCat]
      this.insideVal = price
      this.$emit('input', price)
    },
    onblur(e) {
      const value = e.target.value
      this.$emit('input', value)
    },

    onFocus() {
      this.isShowDrop = true
    },
    onkeydown(e) {
      const { keyCode } = e
      if (keyCode === 38) {
        const optionsData = this.optionsData
        let targetIndex = this.currentIndex - 1
        const maxIndex = optionsData.length - 1
        if (targetIndex < 0) {
          targetIndex = maxIndex
        }
        this.currentIndex = targetIndex
      }
      if (keyCode === 40) {
        const optionsData = this.optionsData
        let targetIndex = this.currentIndex + 1
        const maxIndex = optionsData.length - 1
        if (targetIndex > maxIndex) {
          targetIndex = 0
        }
        this.currentIndex = targetIndex
      }
      if (keyCode === 13) {
        const optionsData = this.optionsData
        const currentIndex = this.currentIndex
        const currentRow = optionsData[currentIndex]
        this.handleSelectOption(currentRow)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.optionsWrapper{
  position:absolute; z-index: 100;
  border:solid 2px #3198ff;
  width:100%;
  background: #fff;
  ul{
    padding: 0; margin: 0;
  }
  a.current{
    background: #eeeeee;
  }
  a, a:link{
    display: block;
    padding:5px 0 5px 5px;
    border-bottom: solid 1px #eeeeee
  }
  a:hover{
    background: #eeeeee;
  }
}
</style>
